angular.module('app.controllers', [])
    .controller('AppController', function($rootScope, $scope, Tools, dataApi) {
        $scope.$on('$viewContentLoaded', function() {
            //appHandle.initComponents();
        });
        $rootScope.sysConfigs.paginationTmpl = sysConfigs.sdir + "/admin/views/tpl/pagination.html?4";
        $rootScope.sysConfigs.pageSize = 10;
        $rootScope.sysConfigs.pageMax = 5;
        $rootScope.sysConfigs.viewSize = function() {
            var w = $("body").width();
            if (w >= 1200) {
                //lg
                return 3;
            } else if (w >= 992) {
                //md
                return 2;
            } else if (w >= 768) {
                //sm
                return 1;
            } else {
                //xs
                return 0;
            }
        }();
        dataApi.getDicts().then(function(data) {
            $rootScope.sysConfigs = angular.extend($rootScope.sysConfigs, data.configs);
            $rootScope.sysDicts = data;
        });
        var h = $(window).height() - 101;
        $scope.pageContentStyle = {
            "min-height": h + "px",
        };
        $rootScope.getCompanys = function(val) {
            var pageData = {
                limit: $scope.sysConfigs.pageSize,
                offset: 0,
                pagenum: 1,
                fields: "Cname,Id",
                query: "",
                rnd: Tools.timeStamp(),
            };
            if (val) {
                pageData.query = "Cname.icontains:" + val;
            }
            return dataApi.GgcmsCompanyList(pageData).then(
                function(data) {
                    if (data.Code == 0) {
                        return data.Data.List;
                    }
                    return [];
                }
            );
        };
    })
    .controller('HeaderController', function($scope, $rootScope, Tools, appHandle, dataApi) {
        $scope.$on('$includeContentLoaded', function() {
            appHandle.initHeader(); // init header
        });
        $scope.clearCache = function() {
            var clearCacth = dataApi.clearCacth();
            clearCacth.then(function(data) {
                console.log(data);
            });
        };
        $scope.pageSidebarToggler = function() {
            console.log($rootScope.sysConfigs);
            $rootScope.sysConfigs.pageSidebarClosed = !$rootScope.sysConfigs.pageSidebarClosed;
        }

        $scope.logout = function() {
            Tools.alert({
                icon: "question",
                title: "是否要退出登录？",
                buttons: [{
                    name: "是",
                    click: function() {
                        var logout = dataApi.logout();
                        logout.then(function(data) {
                            if (data.Code == 0) {
                                location.reload();
                            } else {
                                Tools.loading(
                                    "<h2>" + rdata.Msg + "</h2>",
                                    800
                                );
                            }
                        });
                    }
                }, {
                    className: "btn-lg red",
                    name: "否"
                }]
            });
        };
    })
    .controller('SidebarController', function($scope, $rootScope, $location, $stateParams, $state, dataApi, sidebarMenu) {
        $scope.$on('$includeContentLoaded', function() {
            // var getPowers = dataApi.getPowers();
            // getPowers.then(function(data) {
            //     $rootScope.$sideMenus = data;
            // });
        });
        var curl = $location.url();
        $scope.currentData = { openid: -1 };
        var firstShow = function(menus) {
            menus.forEach(function(m) {
                if (m.subMenu) {
                    firstShow(m.subMenu);
                }
                if (m.url == curl) {
                    $scope.currentData.menuid = m.id;
                    $scope.currentData.openid = m.id;
                    return;
                }
            }, this);
        };
        firstShow(sidebarMenu);
        //替换末尾的add再匹配一次
        if ($scope.currentData.openid == -1) {
            curl = curl.split("?")[0].replace(/Add\.html$/i, "List.html");
            firstShow(sidebarMenu);
        }
        $scope.sidebarMenu = sidebarMenu;
        $scope.menuClick = function(menu) {
            $scope.currentData.menuid = menu.id;
            $location.url(menu.url);
        };
        $scope.menuActive = function(menu) {
            if (menu.tagname) {
                return menu.tagname.indexOf($scope.currentData.menuid) != -1;
            }
            return $scope.currentData.menuid == menu.id;
        };
    })
    .controller('FooterController', function($scope, appHandle) {
        $scope.$on('$includeContentLoaded', function() {
            appHandle.initFooter(); // init footer
        });
    })
    .controller('loginCtrl', function($scope, dataApi, Tools, md5) {
        console.log("loginCtrl");
        //背景切换
        $.backstretch([
            sysConfigs.sdir + "/img/bg/1.jpg",
            sysConfigs.sdir + "/img/bg/2.jpg",
            sysConfigs.sdir + "/img/bg/3.jpg",
            sysConfigs.sdir + "/img/bg/4.jpg"
        ], {
            fade: 1000,
            duration: 8000
        });
        $scope.data = {};
        $scope.getCaptchaUrl = function() {
            $scope.captchaUrl = "/getCaptcha?rnd=" + Tools.timeStamp();
        };
        $scope.getCaptchaUrl();
        $scope.loginSubmit = function(data) {
            Tools.loading();
            $scope.posting = true;
            var ndata = angular.copy(data);
            ndata.password = md5.createHash(md5.createHash(data.password) + data.captcha);
            dataApi.loginSubmit(ndata)
                .then(function(rdata) {
                    Tools.removeLoading();
                    if (rdata.Code != 0) {
                        $scope.posting = false;
                        $scope.getCaptchaUrl();
                        Tools.loading(
                            "<h2>" + rdata.Msg + "</h2>",
                            800
                        );
                    } else {
                        window.location.href = "./AdminHome"
                    }
                    console.log(rdata);
                }, function(err) {
                    $scope.posting = false;
                });
        };
    })
    .controller('homeCtrl', function($scope) {

    })
    .controller('GgcmsAdsListCtrl', function($scope, $timeout, dataApi, listSvr, Tools) {
        $scope.currentInfo = {
            currentPage: 1,
            query: ""
        };
        listSvr.init($scope);
        $scope.listSvr = listSvr;
        listSvr.listDataLoad($scope.currentInfo.pagenum, $scope.currentInfo.query);
    })
    .controller('GgcmsAdsAddCtrl', function($scope, $location, dataApi, editSvr, Tools) {
        editSvr.init($scope);
        $scope.editSvr = editSvr;
        var id = $location.search().id || 0;
        $scope.currentInfo = {};
        if (id != 0) {
            editSvr.getinfo(id);
        } else {
            $scope.data = {

                "Id": 0,
                "Adtype": 0,
                "Title": "",
                "Imgurl": "",
                "Sortid": 0,
                "Status": 0,
                "Describe": "",
                "Extattr1": "",
                "Extattr2": "",
                "Extattr3": "",
                "Tourl": "",
                "AdsCode": ""
            };
        }
        $scope.saveData = function(data) {
            var ndata = angular.copy(data);
            ndata.Adtype = ndata.Adtype.toString();
            editSvr.update(ndata)
        };
    })
    .controller('GgcmsAssessListCtrl', function($scope, $timeout, dataApi, listSvr, Tools) {
        $scope.currentInfo = {
            currentPage: 1,
            query: ""
        };
        listSvr.init($scope);
        $scope.listSvr = listSvr;
        listSvr.listDataLoad($scope.currentInfo.pagenum, $scope.currentInfo.query);
        $scope.$on("listDataLoaded", function(ev, data) {
            var users = [];
            var tutorials = [];
            data.List.forEach(function(item) {
                if (users.indexOf(item.Userid) == -1) {
                    users.push(item.Userid);
                }
                if (tutorials.indexOf(item.TutorialId) == -1) {
                    tutorials.push(item.TutorialId);
                }
            }, this);
            var pageData = {
                limit: 1000,
                offset: 0,
                pagenum: 1,
                query: "Id.in:" + tutorials.join("|"),
                fields: "Id,Title",
                rnd: Tools.timeStamp(),
            };
            dataApi.GgcmsTutorialList(pageData).then(function(tlist) {
                console.log(tlist);
                $scope.currentInfo.tlist = tlist.Data.List;
                pageData.query = "Id.in:" + users.join("|");
                pageData.fields = "Id,Userid,Realname";
                return dataApi.GgcmsUsersList(pageData);
            }).then(function(ulist) {
                $scope.currentInfo.ulist = ulist;
                console.log(ulist);
                data.List.forEach(function(item) {
                    ulist.Data.List.forEach(function(user) {
                        if (user.Id == item.Userid) {
                            item.Username = user.Userid;
                            item.Realname = user.Realname;
                            return;
                        }
                    }, this);
                    $scope.currentInfo.tlist.forEach(function(tinfo) {
                        if (tinfo.Id == item.TutorialId) {
                            item.Title = tinfo.Title;
                            return;
                        }
                    }, this);
                }, this);
            });
        });

    })
    .controller('GgcmsArticleListCtrl', function($scope, $location, $timeout, dataApi, listSvr, Tools) {
        $scope.currentInfo = {
            currentPage: 1,
            query: "Category_Id.gt:0",
        };
        listSvr.init($scope);
        $scope.listSvr = listSvr;
        listSvr.listDataLoad($scope.currentInfo.pagenum, $scope.currentInfo.query);
        var pageData = {
            limit: 1000,
            offset: 0,
            pagenum: 1,
            query: "",
            sortby: "Orderid",
            order: "asc",
            fields: "Id,CategoryName,ParentId",
            rnd: Tools.timeStamp(),
        };
        $scope.$on("listDataLoaded", function(ev, data) {
            var CategoryList = [];
            if ($scope.data.List && $scope.data.List.length > 0) {
                var list = [];
                $scope.data.List.forEach(function(item) {
                    if (list.indexOf(item.Categoryid) == -1) {
                        list.push(item.Categoryid);
                    }
                }, this);
                pageData.query = "CategoryType:0"; //,Id.in:" + list.join("|");
                dataApi.GgcmsCategoryList(pageData).then(function(data) {
                    if (data.Code == 0) {
                        if (data.Data.List) {
                            CategoryList = data.Data.List;
                            $scope.data.List.forEach(function(item) {
                                item.CategoryName = "顶级分类";
                                CategoryList.forEach(function(cate) {
                                    if (item.Categoryid == cate.Id) {
                                        item.CategoryName = cate.CategoryName;
                                        return;
                                    }
                                }, this);
                            }, this);
                        }
                    }
                });
            }
        });
    })
    .controller('GgcmsArticleAddCtrl', function($scope, $location, $timeout, dataApi, editSvr, Tools) {
        editSvr.init($scope);
        $scope.editSvr = editSvr;
        var id = $location.search().id || 0;
        $scope.currentInfo = {
            detailShow: false,
            expandedNodes: [],
        };
        if (id != 0) {
            editSvr.getinfo(id);
            $scope.$on("infoDataLoaded", function(event, data) {
                if ($scope.data.Categoryid == 0) {
                    $scope.data.CategoryName = "请选择分类";
                }
                if ($scope.data.AttaList) {
                    editSvr.attrSort();
                    $scope.data.AttaList.forEach(function(item) {
                        item.btnName = "btnAtta_" + item.Sortid;
                        item.nid = item.Sortid;
                    }, this);
                }
                categoryLoad();
            });
        } else {
            $scope.data = {
                "Id": 0,
                "Content": "",
                "Title": "",
                "Category_Id": 0,
                "CategoryName": "请选择分类",
                "TitleImg": "",
                "RedirectUrl": "",
                "Author": "",
                "Source": "",
                "SourceUrl": "",
                "Keywords": "",
                "Description": "",
                "ShowType": 0,
                "ShowLevel": 0,
            };
            $timeout(function() {
                categoryLoad();
            });
        }
        var categoryLoad = function() {
            var pageData = {
                limit: 1000,
                offset: 0,
                pagenum: 1,
                query: "CategoryType:0",
                sortby: "OrderId",
                order: "asc",
                fields: "Id,CategoryName,ParentId",
                rnd: Tools.timeStamp(),
            };
            dataApi.GgcmsCategoryList(pageData).then(function(data) {
                if (data.Code == 0) {
                    var topNode = {
                        Id: 0,
                        CategoryName: "请选择分类",
                        children: categoryInit(0, data.Data.List)
                    };
                    $scope.currentInfo.dataForTheTree = [topNode];
                    if (!$scope.currentInfo.selectNode) {
                        $scope.currentInfo.selectNode = topNode;
                    }
                    $scope.currentInfo.expandedNodes.push(topNode);
                }
            });
        };
        $scope.treeOptions = {
            nodeChildren: "children",
            dirSelectable: true,
            injectClasses: {
                ul: "a1",
                li: "a2",
                liSelected: "a7",
                iExpanded: "a3",
                iCollapsed: "a4",
                iLeaf: "a5",
                label: "a6",
                labelSelected: "a8"
            }
        }
        var categoryInit = function(pid, list) {
            var categorys = [];
            list.forEach(function(item) {
                if (item.ParentId == pid) {
                    var subitems = categoryInit(item.Id, list);
                    var obj = angular.copy(item);
                    if (subitems.length > 0) {
                        obj.children = subitems;
                        $scope.currentInfo.expandedNodes.push(obj);
                    }
                    categorys.push(obj);
                }
                if (item.Id == $scope.data.Categoryid) {
                    $scope.data.CategoryName = item.CategoryName;
                    if (!$scope.currentInfo.selectNode) {
                        $scope.currentInfo.selectNode = categorys[categorys.length - 1];
                    }
                }
            }, this);
            return categorys;
        };

        $scope.showSelected = function(node) {
            $scope.currentInfo.selectNode = node;
            $scope.data.Category_Id = node.Id;
            $scope.data.CategoryName = node.CategoryName;
            $scope.currentInfo.showCategoryTree = !$scope.currentInfo.showCategoryTree;
        };
        $scope.saveData = function(data) {
            var ndata = angular.copy(data);
            if (data.AttaList && data.AttaList.length > 0) {
                editSvr.attrSort();
                var AttaList = [];
                var sid = 0;
                data.AttaList.forEach(function(item) {
                    if (item.Attaurl || item.Id > 0) {
                        var obj = angular.copy(item);
                        if (!obj.Attaurl) {
                            obj.AttaType = -1;
                        } else {
                            sid++;
                            obj.Sortid = sid;
                        }
                        delete obj.nid;
                        delete obj.file;
                        delete obj.btnName;
                        AttaList.push(obj);
                    }
                }, this);
                ndata.AttaList = AttaList;
            }
            editSvr.update(ndata);
        };
    })
    .controller('GgcmsCategoryListCtrl', function($scope, $timeout, $location, $state, dataApi, listSvr, Tools) {
        $scope.currentInfo = {
            currentPage: 1,
            query: "GgcmsCategoryList",
            listSvrName: "",
            CategoryType: $location.search().CategoryType || "0",
        };
        $scope.currentInfo.addLink = "#/GgcmsCategoryAdd.html?userType=" + $scope.currentInfo.userType + "&systype=" + $scope.currentInfo.systype
        listSvr.init($scope);
        $scope.listSvr = listSvr;
        var pageData = {
            limit: 1000,
            offset: 0,
            pagenum: 1,
            query: "",
            sortby: "Orderid",
            order: "asc",
            fields: "Id,CategoryName,ParentId",
            rnd: Tools.timeStamp(),
        };
        pageData.query = "CategoryType:" + $scope.currentInfo.CategoryType || 0;

        $scope.deleteOne = function(item) {
            $scope.data.List.forEach(function(cat) {
                if (cat.Id == item.id) {
                    cat.optChecked = true;
                } else {
                    cat.optChecked = false;
                }
            }, this);
            listSvr.deleteItem();
        };
        dataApi.GgcmsCategoryList(pageData).then(function(data) {
            if (data.Code == 0) {
                $scope.data = data.Data;
                $scope.currentInfo.cateData = categoryInit(0, data.Data.List);
            }
        });
        $scope.showSortSaveBtn = false;
        $scope.sortChange = function() {
            $scope.showSortSaveBtn = true;
        };
        var datalist = [];
        $scope.sortSave = function() {
            datalist = [];
            GetSortData($scope.currentInfo.cateData, 0, 0);
            dataApi.GgcmsCategorySaveSort(datalist).then(function(data) {
                if (data.Code == 0) {
                    $scope.showSortSaveBtn = false;
                    Tools.loading("<h3>排序保存成功</h3>", 800);
                } else {
                    Tools.alert({
                        "icon": "error",
                        "title": data.Msg,
                    });
                }
            });
        };
        var GetSortData = function(list, pid, level, path) {
            level++;
            for (i in list) {
                var item = {};
                var c = 0;
                if (list[i].children && list[i].children.length > 0) {
                    c = list[i].children.length;
                }
                item = {
                    Id: list[i].item.id,
                    Child: c,
                    Orderid: datalist.length,
                    ParentId: pid,
                    Depth: level,
                    Ppath: pid == 0 ? list[i].item.id.toString() : path + "," + list[i].item.id
                };
                datalist.push(item);
                if (c > 0) {
                    GetSortData(list[i].children, list[i].item.id, level, item.Ppath);
                }
            }
        }
        var categoryInit = function(pid, list) {
            var categorys = [];
            if (list) {
                list.forEach(function(item) {
                    if (item.ParentId == pid) {
                        var subitems = categoryInit(item.Id, list);
                        var obj = {
                            item: {
                                id: item.Id,
                                text: item.CategoryName,
                                child: subitems.length
                            }
                        };
                        if (subitems.length > 0) {
                            obj.children = subitems;
                        }
                        categorys.push(obj);
                    }
                }, this);
            }
            return categorys;
        };
    })
    .controller('GgcmsCategoryAddCtrl', function($scope, $location, dataApi, editSvr, Tools) {
        editSvr.init($scope);
        $scope.editSvr = editSvr;
        var id = $location.search().id || 0;
        $scope.currentInfo = {
            showCategoryTree: false,
            expandedNodes: [],
            CategoryType: $location.search().CategoryType || "0",
        };
        if (id != 0) {
            editSvr.getinfo(id);
            $scope.$on("infoDataLoaded", function(event, data) {
                console.log(data);
            });
        } else {
            $scope.data = {
                "Id": 0,
                "CategoryName": "",
                "Logo": "",
                "ParentId": 0,
                "parentName": "顶级分类",
                "Curl": "",
                "Description": "",
                "Content": "",
                "Extattrib": "",
                "CategoryType": 0,
            };
        }
        $scope.treeOptions = {
            nodeChildren: "children",
            dirSelectable: true,
            injectClasses: {
                ul: "a1",
                li: "a2",
                liSelected: "a7",
                iExpanded: "a3",
                iCollapsed: "a4",
                iLeaf: "a5",
                label: "a6",
                labelSelected: "a8"
            }
        }
        var pageData = {
            limit: 1000,
            offset: 0,
            pagenum: 1,
            query: "CategoryType:" + $scope.currentInfo.CategoryType,
            sortby: "Orderid",
            order: "asc",
            fields: "Id,CategoryName,ParentId",
            rnd: Tools.timeStamp(),
        };
        dataApi.GgcmsCategoryList(pageData).then(function(data) {
            if (data.Code == 0) {
                var topNode = {
                    Id: 0,
                    CategoryName: "顶级分类",
                    children: categoryInit(0, data.Data.List)
                };
                $scope.currentInfo.dataForTheTree = [topNode];
                $scope.currentInfo.selectNode = topNode;
                $scope.currentInfo.expandedNodes.push(topNode);
            }
        });
        var categoryInit = function(pid, list) {
            var categorys = [];
            if (list && list.length > 0) {
                list.forEach(function(item) {
                    if (item.ParentId == pid) {
                        var subitems = categoryInit(item.Id, list);
                        var obj = angular.copy(item);
                        if (subitems.length > 0) {
                            obj.children = subitems;
                            $scope.currentInfo.expandedNodes.push(obj);
                        }
                        categorys.push(obj);
                    }
                }, this);
            }
            return categorys;
        };
        $scope.showSelected = function(node) {
            $scope.currentInfo.selectNode = node;
            $scope.data.ParentId = node.Id;
            $scope.data.parentName = node.CategoryName;
            $scope.currentInfo.showCategoryTree = !$scope.currentInfo.showCategoryTree;
        };
    })
    .controller('GgcmsCompanyListCtrl', function($scope, $timeout, dataApi, listSvr, Tools) {
        $scope.currentInfo = {
            currentPage: 1,
            query: ""
        };
        listSvr.init($scope);
        $scope.listSvr = listSvr;
        listSvr.listDataLoad($scope.currentInfo.pagenum, $scope.currentInfo.query);
    })
    .controller('GgcmsCompanyAddCtrl', function($scope, $timeout, $location, dataApi, editSvr, Tools) {
        editSvr.init($scope);
        $scope.editSvr = editSvr;
        var id = $location.search().id || 0;
        $scope.currentInfo = {};
        if (id != 0) {
            editSvr.getinfo(id);
        } else {
            $timeout(function() {
                $scope.data = {
                    "Id": 0,
                    "Cname": "",
                    "Address": "",
                    "Clogo": "",
                    "Phone": "",
                    "Contacts": "",
                    "Tmpldir": editSvr.getDefaultStyle("companyStyle").type,
                    "Systype": $scope.sysConfigs.loginUser.Systype || "0",
                };
            });
        }
    })
    .controller('GgcmsExamRecordListCtrl', function($scope, $timeout, dataApi, listSvr, Tools) {
        $scope.currentInfo = {
            currentPage: 1,
            query: ""
        };
        listSvr.init($scope);
        $scope.listSvr = listSvr;
        listSvr.listDataLoad($scope.currentInfo.pagenum, $scope.currentInfo.query);
    })
    .controller('GgcmsExamRecordAddCtrl', function($scope, $location, dataApi, editSvr, Tools) {
        editSvr.init($scope);
        $scope.editSvr = editSvr;
        var id = $location.search().id || 0;
        $scope.currentInfo = {};
        if (id != 0) {
            editSvr.getinfo(id);
        } else {
            $scope.data = {

                "Id": 0,
                "Tutorialid": "",
                "Userid": "",
                "Cdate": "",
                "Score": "",
                "Correct": "",
                "Wrong": "",
                "Datekey": "",
            };
        }
    })
    .controller('GgcmsLearnRecordListCtrl', function($scope, $timeout, dataApi, listSvr, Tools) {
        $scope.currentInfo = {
            currentPage: 1,
            query: ""
        };
        listSvr.init($scope);
        $scope.listSvr = listSvr;
        listSvr.listDataLoad($scope.currentInfo.pagenum, $scope.currentInfo.query);
    })
    .controller('GgcmsLearnRecordAddCtrl', function($scope, $location, dataApi, editSvr, Tools) {
        editSvr.init($scope);
        $scope.editSvr = editSvr;
        var id = $location.search().id || 0;
        $scope.currentInfo = {};
        if (id != 0) {
            editSvr.getinfo(id);
        } else {
            $scope.data = {

                "Id": 0,
                "Userid": "",
                "Tutorialid": "",
                "Cdate": "",
                "Duration": "",
                "Datekey": "",
            };
        }
    })
    .controller('GgcmsQuestionsListCtrl', function($scope, $location, $timeout, dataApi, listSvr, Tools) {
        var group = $location.search().ugroup || "";
        $scope.currentInfo = {
            currentPage: 1,
            selectUserGroup: group,
        };
        if (group != "") {
            group = parseInt(group);
            $scope.currentInfo.selectUserGroup = group;
            $scope.currentInfo.query = "groupId:" + group;
            $scope.currentInfo.listSvrName = "GetQuestionsList";
        }
        listSvr.init($scope);
        $scope.listSvr = listSvr;
        listSvr.listDataLoad($scope.currentInfo.pagenum, $scope.currentInfo.query);
        $scope.$on("listDataLoaded", function(ev, data) {
            console.log(data);
        });
        dataApi.getSysDicts("UserGroup", false).then(function(gudata) {
            gudata.unshift({ Dkey: "全部", Id: "" });
            $scope.currentInfo.UserGroup = gudata;
        });
        $scope.userGroupChange = function(item) {
            if (item == group) {
                return;
            }
            if (item == "") {
                $location.search('ugroup', null);
            } else {
                $location.search('ugroup', item);
            }
        };
    })
    .controller('GgcmsQuestionsAddCtrl', function($scope, $timeout, $location, dataApi, editSvr, Tools) {
        editSvr.init($scope);
        $scope.editSvr = editSvr;
        var id = $location.search().id || 0;
        var group = $location.search().ugroup || "";
        $scope.currentInfo = {
            maxAnswer: 10,
            expandedNodes: [],
            selectUserGroup: group,
        };
        var answerAutoId = 0;
        dataApi.getSysDicts("UserGroup", false).then(function(ugdata) {
            $scope.currentInfo.UserGroup = ugdata;
            if (id != 0) {
                editSvr.getinfo(id);
                $scope.$on("infoDataLoaded", function(event, data) {
                    $scope.data.Tutorialid = {
                        "Id": $scope.data.Tutorialid,
                        "Title": $scope.data.TutorialName
                    };
                    if ($scope.data.OptionsList) {
                        answerSort();
                        $scope.data.OptionsList.forEach(function(item) {
                            item.btnName = "btnAtta_" + item.Sortid;
                            item.nid = item.Sortid;
                        }, this);
                    }
                    if ($scope.data.UserGroup && $scope.data.UserGroup.length > 0) {
                        $scope.data.UserGroups = $scope.data.UserGroup.sort().join(",");
                        ugdata.forEach(function(item) {
                            if ($scope.data.UserGroup.indexOf(item.Id) != -1) {
                                item.checked = true;
                            }
                        }, this);
                    }
                });
            } else {
                $scope.data = {
                    "Id": 0,
                    "Title": "",
                    "Content": "",
                    "Answer": "",
                    "Qtype": 0,
                    "Score": 0,
                    "UserGroups": "",
                    "UserGroup": [],
                    "OptionsList": []
                };
                if (group) {
                    $scope.data.UserGroups = group;
                    ugdata.forEach(function(item) {
                        if (group.indexOf(item.Id) != -1) {
                            item.checked = true;
                        }
                    }, this);
                }
                $timeout(function() {
                    $scope.answerInit();
                });
            }
        });

        $scope.userGroupCheck = function(item) {
            var ugrp = [];
            $scope.currentInfo.UserGroup.forEach(function(item) {
                if (item.checked) {
                    ugrp.push(item.Id);
                }
            }, this);
            $scope.data.UserGroups = ugrp.sort().join(",");
            $scope.data.UserGroup = ugrp;
        };
        var answerSort = function() {
            if (!$scope.data.OptionsList) {
                return;
            }
            var list = $scope.data.OptionsList.sort(function(a, b) {
                return a.Sortid * 10 - b.Sortid * 10;
            });
            for (var i = 0, j = 0; i < list.length; i++) {
                if (list[i].DelTag == -1) {
                    continue;
                }
                j++;
                list[i].Sortid = j;
            }
        };
        //设置正确答案
        $scope.answerSet = function($event, sortid) {
            if ($event) {
                $event.preventDefault($event);
            }
            //多选
            if ($scope.data.Qtype == 2) {
                var answer = $scope.answerLetter(sortid);
                var aws = $scope.data.Answer.split(",");
                var idx = aws.indexOf(answer);
                if (idx == -1) {
                    //增加
                    aws.push(answer);
                } else {
                    aws.splice(idx, 1);
                    //删除
                }
                var answer = aws.sort().join(",")
                console.log(answer);
                $scope.data.Answer = answer;
            } else {
                //单选或判断
                $scope.data.Answer = $scope.answerLetter(sortid);
            }
        };
        $scope.answerInit = function() {
            var qtype = $scope.sysDicts.questType[0];
            $scope.sysDicts.questType.forEach(function(item) {
                if (item.type == $scope.data.Qtype) {
                    qtype = item;
                    return;
                }
            }, this);
            if (!$scope.data.OptionsList) {
                $scope.data.OptionsList = [];
            }
            var c = qtype.itemNum - $scope.data.OptionsList.length;
            //标准多于实际，添加
            if (c > 0) {
                for (var i = 0; i < c; i++) {
                    $scope.answerAdd();
                }
            } else if (c < 0) {
                //标准小于实际，删除
                for (var i = 0; i < Math.abs(c); i++) {
                    var len = $scope.data.OptionsList.length;
                    $scope.answerDelete($scope.data.OptionsList[len - 1]);
                }
            }
        }
        $scope.answerLetter = function(sortid) {
            return String.fromCharCode(sortid + 64);
        };
        $scope.answerUpDown = function(item, step) {
            if (!$scope.data.OptionsList) {
                return;
            }
            item.Sortid = item.Sortid + step;
            answerSort();
        };
        $scope.answerCount = function() {
            if (!$scope.data.OptionsList) {
                return 0;
            }
            var arr = $.grep($scope.data.OptionsList, function(n, i) {
                return n.DelTag != -1;
            });
            return arr.length;
        };
        $scope.answerDelete = function(item) {
            if (!$scope.data.OptionsList) {
                return;
            }
            if ($scope.data.Qtype == 2) {
                //多选
                $scope.answerSet(null, item.Sortid);
            } else {
                //单选或判断
                var answer = $scope.answerLetter(item.Sortid);
                if (answer == $scope.data.Answer) {
                    $scope.data.Answer = "";
                }
            }
            editSvr.updataFileList(false, item.AnswerPic);
            if (item.Id > 0) {
                item.DelTag = -1;
            } else {
                var idx = $scope.data.OptionsList.indexOf(item);
                if (idx != -1) {
                    $scope.data.OptionsList.splice(idx, 1);
                }
            }
            answerSort();
        };
        $scope.answerAdd = function() {
            if ($scope.answerCount() >= $scope.currentInfo.maxAnswer) {
                Tools.loading("<h3>答案最多不能超过 " + $scope.currentInfo.maxAnswer + " 条</h3>", 1000);
                return;
            }
            if (!$scope.data.OptionsList) {
                $scope.data.OptionsList = [];
                answerAutoId = 0;
            }
            if (!answerAutoId) {
                answerAutoId = $scope.data.OptionsList.length;
            }
            answerAutoId++;
            var answerItem = {
                "Id": 0,
                "Answer": "答案" + answerAutoId,
                "AnswerPic": "",
                "Sortid": answerAutoId,
                "DelTag": 0,
                "nid": answerAutoId,
                "btnName": "btnAtta_" + answerAutoId,
            };
            $scope.data.OptionsList.push(answerItem);
            answerSort();
        };
        $scope.saveData = function(data) {
            var ndata = angular.copy(data);
            delete ndata.UserGroups;
            if (angular.isObject(ndata.Tutorialid)) {
                ndata.Tutorialid = ndata.Tutorialid.Id;
            }
            editSvr.update(ndata);
        };
    })
    .controller('GgcmsSysdictsListCtrl', function($scope, $timeout, $location, dataApi, listSvr, Tools, localStorageService) {
        $scope.currentInfo = {
            currentPage: 1,
            group: $location.search().group || "",
        };
        $scope.$on('$stateChangeSuccess', function(event, toState, toParams, fromState, fromParams) {
            var sname = "sysdict-" + $scope.currentInfo.group;
            localStorageService.clear(sname);
        });
        $scope.currentInfo.query = "Dgroup:" + $scope.currentInfo.group;
        listSvr.init($scope);
        $scope.listSvr = listSvr;
        listSvr.listDataLoad($scope.currentInfo.pagenum, $scope.currentInfo.query);
    })
    .controller('GgcmsSysdictsAddCtrl', function($scope, $location, dataApi, editSvr, Tools) {
        editSvr.init($scope);
        $scope.editSvr = editSvr;
        var id = $location.search().id || 0;
        $scope.currentInfo = {
            group: $location.search().group || "",
        };
        if (id != 0) {
            editSvr.getinfo(id);
        } else {
            $scope.data = {
                "Id": 0,
                "Dkey": "",
                "Dval": "",
                "Dgroup": $scope.currentInfo.group,
                "Pval": "",
            };
        }

    })
    .controller('GgcmsTutorialListCtrl', function($scope, $timeout, $location, dataApi, listSvr, Tools) {
        var group = $location.search().ugroup || "";
        $scope.currentInfo = {
            currentPage: 1,
            selectUserGroup: group,
        };
        if (group != "") {
            group = parseInt(group);
            $scope.currentInfo.selectUserGroup = group;
            $scope.currentInfo.query = "groupId:" + group;
            $scope.currentInfo.listSvrName = "GetTutorialList";
        }
        listSvr.init($scope);
        $scope.listSvr = listSvr;
        listSvr.listDataLoad($scope.currentInfo.pagenum, $scope.currentInfo.query);
        $scope.$on("listDataLoaded", function(ev, data) {});
        dataApi.getSysDicts("UserGroup", false).then(function(gudata) {
            gudata.unshift({ Dkey: "全部", Id: "" });
            $scope.currentInfo.UserGroup = gudata;
        });
        $scope.userGroupChange = function(item) {
            if (item == group) {
                return;
            }
            if (item == "") {
                $location.search('ugroup', null);
            } else {
                $location.search('ugroup', item);
            }
        };
    })
    .controller('GgcmsTutorialAddCtrl', function($scope, $location, $timeout, dataApi, editSvr, Tools) {
        editSvr.init($scope);
        $scope.editSvr = editSvr;
        var id = $location.search().id || 0;
        var group = $location.search().ugroup || "";
        $scope.currentInfo = {
            detailShow: false,
            selectUserGroup: group,
        };
        dataApi.getSysDicts("UserGroup", false).then(function(ugdata) {
            $scope.currentInfo.UserGroup = ugdata;
            if (id != 0) {
                editSvr.getinfo(id);
                $scope.$on("infoDataLoaded", function(event, data) {
                    if ($scope.data.AttaList) {
                        editSvr.attrSort();
                        $scope.data.AttaList.forEach(function(item) {
                            item.btnName = "btnAtta_" + item.Sortid;
                            item.nid = item.Sortid;
                        }, this);
                    }
                    if ($scope.data.UserGroup && $scope.data.UserGroup.length > 0) {
                        $scope.data.UserGroups = $scope.data.UserGroup.sort().join(",");
                        ugdata.forEach(function(item) {
                            if ($scope.data.UserGroup.indexOf(item.Id) != -1) {
                                item.checked = true;
                            }
                        }, this);
                    }
                });
            } else {
                $scope.data = {
                    "Id": 0,
                    "Description": "",
                    "Title": "",
                    "Content": "",
                    "Thumbnail": "",
                    "VideoUrl": "",
                    "UserGroups": "",
                    "UserGroup": [],
                };
                if (group) {
                    $scope.data.UserGroups = group;
                    ugdata.forEach(function(item) {
                        if (group.indexOf(item.Id) != -1) {
                            item.checked = true;
                        }
                    }, this);
                }
            }
        });
        $scope.userGroupCheck = function(item) {
            var ugrp = [];
            $scope.currentInfo.UserGroup.forEach(function(item) {
                if (item.checked) {
                    ugrp.push(item.Id);
                }
            }, this);
            $scope.data.UserGroups = ugrp.sort().join(",");
            $scope.data.UserGroup = ugrp;
        };
        $scope.saveData = function(data) {
            var ndata = angular.copy(data);
            delete ndata.UserGroups;
            if (data.AttaList && data.AttaList.length > 0) {
                editSvr.attrSort();
                var AttaList = [];
                var sid = 0;
                data.AttaList.forEach(function(item) {
                    if (item.Attaurl || item.Id > 0) {
                        var obj = angular.copy(item);
                        if (!obj.Attaurl) {
                            obj.AttaType = -1;
                        } else {
                            sid++;
                            obj.Sortid = sid;
                        }
                        delete obj.nid;
                        delete obj.file;
                        delete obj.btnName;
                        AttaList.push(obj);
                    }
                }, this);
                ndata.AttaList = AttaList;
            }
            editSvr.update(ndata);
        };
    })
    .controller('GgcmsUsersListCtrl', function($scope, $timeout, dataApi, listSvr, Tools) {
        $scope.currentInfo = {
            currentPage: 1,
            query: ""
        };

        listSvr.init($scope);
        $scope.listSvr = listSvr;
        dataApi.getSysDicts("UserGroup", false).then(function(data) {
            $scope.currentInfo.UserGroup = data;
            listSvr.listDataLoad($scope.currentInfo.pagenum, $scope.currentInfo.query);
        });
        $scope.getUserGroupKey = function(id) {
            for (var key in $scope.currentInfo.UserGroup) {
                var item = $scope.currentInfo.UserGroup[key];
                if (item.Id == id) {
                    return item.Dkey;
                }
            }
            return "";
        };
        $scope.deleteItem = function() {
            for (var i in $scope.data.List) {
                if ($scope.data.List[i].Id == $scope.sysConfigs.loginUser.Id) {
                    $scope.data.List[i].optChecked = false;
                    break;
                }
            }
            $scope.listSvr.deleteItem();
        };
    })
    .controller('GgcmsUsersAddCtrl', function($scope, $location, dataApi, editSvr, Tools) {
        editSvr.init($scope);
        $scope.editSvr = editSvr;
        var id = $location.search().id || 0;
        $scope.currentInfo = {
            batchRegister: false,
            userIdRegex: '^[a-zA-z0-9]{3,30}$'
        };
        dataApi.getSysDicts("UserGroup", false).then(function(data) {
            $scope.currentInfo.UserGroup = data;
        });

        if (id != 0) {
            editSvr.getinfo(id);
        } else {
            $scope.data = {
                "Id": 0,
                "Usertype": "4",
                "Userid": "",
                "Pwd": "",
                "Realname": "",
                "Email": "",
                "Systype": $scope.sysConfigs.loginUser.Systype,
                "Status": 0,
                "Province": "",
                "City": "",
                "County": "",
                "Phone": "",
                "PostCode": "",
                "Address": "",
                "Avatar": "",
                "Sex": "0"
            };
        }
        $scope.$on("infoDataLoaded", function(event, data) {
            if ($scope.data.CompanyName) {
                $scope.data.Companyid = { Id: $scope.data.Companyid, Cname: $scope.data.CompanyName };
            }
        });
        $scope.cityFilter = function(v1, v2) {
            if ($scope.data && $scope.data.Province) {
                return v1[0] === $scope.data.Province;
            } else {
                return false;
            }
        };
        $scope.areaFilter = function(v1, v2) {
            if ($scope.data && $scope.data.City) {
                return v1[0] === $scope.data.City;
            } else {
                return false;
            }
        };
        dataApi.getAddress().then(function(data) {
            $scope.addressData = data;
        });
        $scope.saveData = function(data) {
            var ndata = {
                Userid: data.Userid,
                Pwd: data.Pwd,
                Sex: data.Sex,
                Companyid: data.Companyid
            };
            var users = ndata.Userid.split(/\s+/);
            var reg = new RegExp($scope.currentInfo.userIdRegex);
            for (var i in users) {
                if (!reg.test(users[i])) {
                    Tools.loading("<h3>用户ID必须是长度为3-30的英文字母或数字</h3>", 1000);
                    return;
                }
            }
            ndata.Userid = users.join(",");
            editSvr.update(ndata);
        };
    })
    .controller('GgcmsMessagesListCtrl', function($scope, $timeout, dataApi, listSvr, Tools) {
        $scope.currentInfo = {
            currentPage: 1,
            query: ""
        };
        listSvr.init($scope);
        $scope.listSvr = listSvr;
        listSvr.listDataLoad($scope.currentInfo.pagenum, $scope.currentInfo.query);
        $scope.$on("listDataLoaded", function(ev, data) {
            var users = [];
            data.List.forEach(function(item) {
                users.push(item.Senduser)
                users.push(item.Recvuser)
            }, this);
            var pageData = {
                query: "Id.in:" + users.join("|"),
                fields: "Id,Userid,Realname",
                rnd: Tools.timeStamp(),
            };
            dataApi.GgcmsUsersList(pageData)
                .then(function(userlist) {
                    userlist.Data.List.forEach(function(item) {
                        data.List.forEach(function(msg) {
                            if (item.Id == msg.Senduser) {
                                msg.SenduserName = item.Realname + "(" + item.Userid + ")";
                            }
                            if (item.Id == msg.Recvuser) {
                                msg.RecvuserName = item.Realname + "(" + item.Userid + ")";
                            }
                        }, this);
                    }, this);
                });
        });
    })
    .controller('GgcmsMessagesAddCtrl', function($scope, $location, dataApi, editSvr, listSvr, Tools) {
        editSvr.init($scope);
        $scope.editSvr = editSvr;
        var id = $location.search().id || 0;
        $scope.currentInfo = {
            currentPage: 1,
            query: "UserType:4",
            fields: "Id,Userid,Realname",
            listSvrName: "GgcmsUsersList",
        };


        if (id != 0) {
            editSvr.getinfo(id);
            $scope.$on("infoDataLoaded", function(ev, data) {
                var users = [];
                users.push(data.Senduser)
                users.push(data.Recvuser)
                var pageData = {
                    query: "Id.in:" + users.join("|"),
                    fields: "Id,Userid,Realname",
                    rnd: Tools.timeStamp(),
                };
                dataApi.GgcmsUsersList(pageData)
                    .then(function(userlist) {
                        userlist.Data.List.forEach(function(item) {
                            if (item.Id == data.Senduser) {
                                data.SenduserName = item.Realname + "(" + item.Userid + ")";
                            }
                            if (item.Id == data.Recvuser) {
                                data.RecvuserName = item.Realname + "(" + item.Userid + ")";
                            }
                        }, this);
                        $scope.source = angular.copy($scope.data);
                        $scope.data.Id = 0;
                        $scope.data.Message = "";
                        $scope.data.Senduser = 0;
                        $scope.data.Recvuser = $scope.source.Senduser;
                        $scope.data.Msgtype = 2;
                        $scope.data.RelationId = $scope.source.Id;
                    });
            });
        } else {
            $scope.data = {
                "Id": 0,
                "Message": "",
                "Senduser": 0,
                "Recvuser": 0,
                "ToUsers": [],
                "touserlist": []
            };
            listSvr.init($scope);
            $scope.listSvr = listSvr;
            listSvr.listDataLoad($scope.currentInfo.pagenum, $scope.currentInfo.query);
        }
        var filterType = 1;
        $scope.userFilter = function(uname, t) {
            uname = uname || "";
            filterType = t;
            if (t == 1) {
                $scope.currentInfo.query = "UserType:4,Userid.icontains:" + uname;
            } else {
                $scope.currentInfo.query = "UserType:4,Realname.icontains:" + uname;
            }
            listSvr.listDataLoad($scope.currentInfo.pagenum, $scope.currentInfo.query);
        };
        $scope.userSelect = function(item) {
            var idx = $scope.data.List.indexOf(item);
            $scope.data.touserlist.push(item);
            $scope.currentInfo.tousers = getUsers("");
        };
        $scope.isSelected = function(item) {
            var ok = false;
            $scope.data.touserlist.forEach(function(user) {
                if (user.Id == item.Id) {
                    ok = true;
                    return;
                }
            }, this);
            return ok;
        };
        $scope.userRemove = function(item) {
            var idx = $scope.data.touserlist.indexOf(item);
            $scope.data.touserlist.splice(idx, 1);
            $scope.currentInfo.tousers = getUsers("");
        };
        var getUsers = function(c) {
            var users = [];
            $scope.data.touserlist.forEach(function(item) {
                users.push(item.Id);
            }, this);
            $scope.data.ToUsers = users;
            return users.join(c);
        };
    });